package com.young.shop.controller;

import com.sun.net.httpserver.HttpServer;
import com.young.shop.pojo.entity.Goods;
import com.young.shop.pojo.vo.BaseRespVO;
import com.young.shop.service.GoodsService;
import com.young.shop.service.impl.GoodsServiceimpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/goodsSearch")
public class GoodsSearchController extends BaseController {

    private GoodsService goodsServiceimpl = new GoodsServiceimpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String searchKeywords = req.getParameter("searchKeywords");

        System.out.println(searchKeywords);

        if (searchKeywords==null){
            List<Goods> allGoods = goodsServiceimpl.getAllGoods();
            List<Goods> goodsList = removeGoodsByStatus(allGoods);
            System.out.println(goodsList);
            writerSucccessBaseRespVoToResponse(resp,goodsList);
            return;
        }

        try {
            List<Goods> goodsList = goodsServiceimpl.queryGoodsByName(searchKeywords);
            List<Goods> goodsList1 = removeGoodsByStatus(goodsList);
            System.out.println(goodsList1);
            writerSucccessBaseRespVoToResponse(resp,goodsList1);
        }catch (RuntimeException e){
            writerFailedBaseRespVoToResponse(resp,e);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }


    public List<Goods> removeGoodsByStatus(List<Goods> list){
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getStatus().equals("已下架")){
                list.remove(i);
            }
        }
        return list;
    }



}
